package com.bloveoacom.weichi.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.StringUtils;

import com.bloveoacom.base.BaseActivity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.http.MessageModel;
import com.bloveoacom.http.RxBus;
import com.bloveoacom.http.RxHelper;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weichi.bean.TransInfoBean;
import com.bloveoacom.weight.DelEditText;
import com.bloveoacom.weight.LlkjToolBar;
import com.jakewharton.rxbinding2.widget.RxTextView;


import org.reactivestreams.Publisher;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bloveoacom.http.MessageModel.TU_TYPE_UPDATEUSERINFO;


public class TransActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    LlkjToolBar mToolbar;
    @BindView(R.id.et_account)
    DelEditText etAccount;
    @BindView(R.id.et_account2)
    TextView et_account2;
    @BindView(R.id.et_number)
    DelEditText etNumber;
    @BindView(R.id.et_memo)
    DelEditText etMemo;
    @BindView(R.id.btn_next)
    TextView btnNext;

    private BottomSheetDialog bottomSheetDialog;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_trans;
    }

    private String memo, to, number, password;

    @Override
    protected View getViewSetTB() {
        return mToolbar;
    }

    @Override
    public void initView() {
        btnNext.setEnabled(false);
    }

    @Override
    public void initData() {
        mToolbar.setToolBar("转账",
                true, "", R.drawable.ic_back, true, "", LlkjToolBar.isNull);
        et_account2.setText(UserInfoBean.getInstance().getWalletAccount());
        setDialog();
        setTransInfo();

    }

    @Override
    public void getBundleExtras(Bundle extras) {

    }

    @Override
    public void initListener() {
        Observable<CharSequence> etAccountOb = RxTextView.textChanges(etAccount);
        Observable<CharSequence> etNumberOb = RxTextView.textChanges(etNumber);
        Disposable subscribe = Observable.combineLatest(etAccountOb, etNumberOb, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2) throws Exception {
                return !StringUtils.isEmpty(charSequence) && !StringUtils.isEmpty(charSequence2) ;
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                btnNext.setEnabled(aBoolean);
            }
        });
       addDispose(subscribe);
    }


    @OnClick(R.id.btn_next)
    public void onViewClicked() {
        to = String.valueOf(etAccount.getText());
        number = String.valueOf(etNumber.getText());
        memo = String.valueOf(etMemo.getText());

        if(Double.parseDouble(number)>0){

        }else{
            ToastUtil.makeShortText(mContext,"请输入大于0的数");
            return;
        }
        viewHolder.tvTransFrom.setText("转出账号    "+UserInfoBean.getInstance().getWalletAccount());
        viewHolder.tvTransTo.setText("转入账号    "+to);
        viewHolder.tvTransNumber.setText("数量   "+number);
        DialogUtil.showDialog(bottomSheetDialog);
    }


    public void trans(){
        showLoadingDialog();
        Disposable dis = HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance().getToken()).subscribeOn(Schedulers.io()).flatMap(new Function<HttpResult<Object>, Publisher<HttpResult<Object>>>() {
            @Override
            public Publisher<HttpResult<Object>> apply(HttpResult<Object> objectHttpResult) throws Exception {
                if(objectHttpResult.isOk()){
                    Object o = objectHttpResult.data;
                    SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                    String s = AESCipher.decryptAES(simpleBean.timeStamp);
                    TransInfoBean transInfoBean = new TransInfoBean(to, number, password, s);
                    String s1 = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean));
                    return HttpMethods.getInstance().getHttpService().userTransfer(UserInfoBean.getInstance().getToken(), s1, memo);
                }else{
                    return Flowable.error(new ApiException(objectHttpResult.code,objectHttpResult.msg));
                }
            }
        }).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<Object>(this){
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                ToastUtil.makeShortText(mContext, "转账成功");
                RxBus.getInstance().send(new MessageModel(TU_TYPE_UPDATEUSERINFO));
                finish();
            }
        });
        addDispose(dis);
    }

    ViewHolder viewHolder;
    public void setTransInfo() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_trans, null);
        viewHolder = new ViewHolder(view);
        bottomSheetDialog = new BottomSheetDialog(mContext);
        bottomSheetDialog.setContentView(view);
        viewHolder.ivClosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.dissDialog(bottomSheetDialog);
            }
        });
        viewHolder.btnTrans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.dissDialog(bottomSheetDialog);
                DialogUtil.showDialog(dialog);
            }
        });
    }

    MaterialDialog dialog;
    private void setDialog() {
        dialog = new MaterialDialog.Builder(mContext)
                .title("输入密码")
                .inputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .positiveText(R.string.sure)
                .negativeText(android.R.string.cancel)
                .cancelable(false)
                .inputRangeRes(6, 20, R.color.colorPrimary)
                .input("请输入密码", "", new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                         password = String.valueOf(input);
                         trans();
                    }
                }).build();

    }



    static class ViewHolder {
        @BindView(R.id.iv_closed)
        ImageView ivClosed;
        @BindView(R.id.tv_order_detail)
        TextView tvOrderDetail;
        @BindView(R.id.tv_trans_from)
        TextView tvTransFrom;
        @BindView(R.id.tv_trans_to)
        TextView tvTransTo;
        @BindView(R.id.tv_trans_number)
        TextView tvTransNumber;
        @BindView(R.id.btn_trans)
        Button btnTrans;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
